package com.eidos.blogs.common.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author ： Eidos
 * @date ：Created in 2020/12/28
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Lazy
@Component
public class RedissonUtils {
    @Lazy
    @Resource(
            name = "redissonClient"
    )
    private RedissonClient redissonClient;

    public RedissonUtils() {
    }

    public RedissonClient getRedissonClient() {
        return this.redissonClient;
    }

    public RLock getLock(String name) {
        return this.getRedissonClient().getLock(name);
    }

    public boolean tryLock(String name, long waitTime, long leaseTime) throws InterruptedException {
        return this.tryLock(this.getLock(name), waitTime, leaseTime);
    }

    public boolean tryLock(RLock lock, long waitTime, long leaseTime) throws InterruptedException {
        return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
    }

    public void unlock(String name) {
        this.unlock(this.getLock(name));
    }

    public void unlock(RLock lock) {
        if (lock.isLocked()) {
            lock.unlock();
        }

    }

    public boolean forceUnlock(String name) {
        return this.forceUnlock(this.getLock(name));
    }

    public boolean forceUnlock(RLock lock) {
        return lock.forceUnlock();
    }
}
